package cn.lsoft.undoner.action;

import cn.lsoft.undoner.model.User;
import cn.lsoft.undoner.service.AdminService;
import cn.lsoft.undoner.util.Contants;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

/**
 * @author <A HREF="mailto:undoner@gmail.com">undoner</A>
 * @date 19-05-2015
 */
@Controller
@RequestMapping("/user")
public class AdminController {
    private static final Logger LOGGER = Logger.getLogger(AdminController.class);

    @Autowired
    private AdminService userService;

    //web index page
    @RequestMapping(value = "login")
    public String indexPage() throws IOException {
        return "/login";
    }

    //login details in install.properties
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public void scheduleLogin(String j_username, String j_password,HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = new User(j_username, j_password);
        if (userService.queryUserByUser(user)) {
            session.setAttribute(Contants.LOGIN, user);
            response.sendRedirect(request.getContextPath() + "/user");
        }
    }
    
    @RequestMapping(value = "")
    public String showFeatures() {
    	 return "/center";
    }

    @RequestMapping(value = "quit")
    public String userQuit(HttpSession session) throws IOException {
        session.removeAttribute(Contants.LOGIN);
        return "/logout";
    }

    @ExceptionHandler(Exception.class)
    public void handleException(Exception e, HttpServletResponse httpServletResponse) throws IOException {
        LOGGER.error(e);
        httpServletResponse.sendError(500);
    }


}
